function solveNQueensBacktrackingWithLasVegas(n, k) {
    function isValid(board, row, col) {
        for (let i = 0; i < row; i++) {
            if (board[i] === col ||
                board[i] - i === col - row ||
                board[i] + i === col + row) {
                return false;
            }
        }
        return true;
    }

    function randomPlacement(board, k) {
        for (let row = 0; row < k; row++) {
            const availableCols = [];
            for (let col = 0; col < n; col++) {
                if (isValid(board, row, col)) {
                    availableCols.push(col);
                }
            }
            if (availableCols.length === 0) {
                return false;
            }
            board[row] = availableCols[Math.floor(Math.random() * availableCols.length)];
        }
        return true;
    }

    function backtrack(board, row) {
        if (row === n) return true;
        for (let col = 0; col < n; col++) {
            if (isValid(board, row, col)) {
                board[row] = col;
                if (backtrack(board, row + 1)) return true;
                board[row] = -1;
            }
        }
        return false;
    }

    while (true) {
        const board = Array(n).fill(-1);
        if (randomPlacement(board, k)) {
            if (backtrack(board, k)) {
                const solution = Array.from({ length: n }, () => Array(n).fill('.'));
                for (let i = 0; i < n; i++) {
                    solution[i][board[i]] = 'Q';
                }
                return solution.map(row => row.join(''));
            }
        }
    }
}
